const mongoose = require('mongoose');
module.exports = (app) => {
 const User = require("../models/User");
 const express = require("express")
 const jwt = require("jsonwebtoken")
 const Request = require("../utils/request")
 const auth = require("../utils/auth")
 const bcrypt = require("bcrypt")
 const router = express.Router({
  // 合并参数
  mergeParams: true,
 })



 // 新建列表
 router.post("/", async (req, res) => {
  if (req.body.carts) {
   req.body.carts = JSON.parse(req.body.carts)
  }
  const model = await req.Model.create(req.body)
  if (model.id) {
   res.send(Request.ok(model))
  } else {
   res.send(Request.err())
  }
 })

 // 编辑列表
 router.put("/:id", async (req, res) => {
  if (req.modelName == "User" && req.body && req.body.password) {
   req.body.password = bcrypt.hashSync(req.body.password, 10)
  }
  const model = await req.Model.findByIdAndUpdate(
   req.params.id,
   req.body,
   { useFindAndModify: false }
  )
  res.send(Request.ok(model))

 })

 // 删除列表
 router.delete("/:id", async (req, res) => {
  await req.Model.findByIdAndDelete(req.params.id)
  res.send(Request.ok())
 })
 const idNames = ['userId']
 // 获取列表
 router.get("/", async (req, res) => {
  let { page, limit, token, ...query } = req.query
  page = parseInt(page)
  limit = parseInt(limit)
  let items;
  let q = {}
  Object.keys(query).forEach(k => {
   if (idNames.some(v => v == k)) {
    q[k] = mongoose.Types.ObjectId(query[k]);
   } else
    q[k] = new RegExp(query[k], 'i')
  })
  if (req.modelName == 'Order') {
   items = {
    total: await req.Model.find(query).countDocuments(),
    docs: await req.Model.aggregate([
     {
      $lookup: {
       from: 'users',
       localField: 'userId',
       foreignField: '_id',
       as: 'userInfo',
      },
     }, {
      $lookup: {
       from: 'goods',
       localField: 'carts.goodId',
       foreignField: '_id',
       as: 'cartsInfo',
      },
     },// 筛选数据  添加字段
     { $match: q },
     { $skip: (page - 1) * limit }, // 跳过文档
     { $limit: limit } // 限制输出结果数量
    ])
   }
  } else {
   items = {
    total: await req.Model.find(q).countDocuments(),
    docs: await req.Model.find(q).skip((page - 1) * limit).limit(limit)
   }
  }
  // populate('parent') 关联取出parent
  // const items = await req.Model.find({

  // }).skip((page - 1) * size).limit(size).setOptions(queryOptions)
  res.send(Request.ok(items))
 })
 // 获取列表详情
 router.get("/:id", async (req, res) => {
  const model = await req.Model.findById(req.params.id)
  res.send(Request.ok(model))
 })

 app.use(
  "/api/auth/:resource",
  auth(),
  (req, res, next) => {
   const modelName = require("inflection").classify(req.params.resource);
   req.Model = require(`../models/${modelName}`)
   req.modelName = modelName
   next()
  },
  router
 )
 // 上传图片接口
 const multer = require("multer")
 // const upload = multer({ dest: __dirname + "/../public/img" })
 const upload = multer({
  storage: multer.diskStorage({
   destination: __dirname + "/../public/img", //配置保存的目录
   // 用于接收上传的内容, 然后给出文件存储时的名称
   filename(req, file, cb) {
    console.log('文件信息:', file);
    // 读取上传的文件名
    const { originalname } = file
    // 从原名称中截取后缀名的部分
    const i = originalname.lastIndexOf('.')
    // 截取 . 开始的内容
    const ext = originalname.substring(i) // .jpg  .png ...这种

    // 生成唯一名称
    const unique_name = Date.now() + ext // v4 是最常用的方案
    console.log('唯一名称:', unique_name);

    // cb : callback缩写, 回调函数. 通过此函数设置文件的存储名称
    // cb(错误信息, 文件存储时的名称)
    cb(null, unique_name)
    // 参数1: null 代表没有错误

    // 直接采用原文件名存在两个BUG
    // 1. 中文文件名 会乱码
    // 2. 同名文件 会覆盖
   }
  })
 })
 app.post(
  "/api/upload",
  // auth(),
  upload.single("file"),
  (req, res) => {
   const file = req.file
   console.log(file);
   file.url = `http://localhost:3000/public/img/${file.filename}`
   res.send(Request.ok(file))
  }
 )
 // 登录
 app.post("/api/login", async function (req, res) {
  let { username, password } = req.body
  const user = await User.findOne({ username })
  if (!user) {
   return res.send(Request.err('用户不存在'));
  }
  // 校验密码
  const isValid = bcrypt.compareSync(password, user.password)
  if (!isValid) {
   return res.send(Request.err('密码错误'))
  }
  const token = jwt.sign({ id: user.id }, app.get("secret"))
  res.send(Request.ok({ token, user }))
 })

 // 注册
 app.post("/api/register", async function (req, res) {
  const user = await User.findOne({ username: req.body.username })
  if (user) {
   return res.send(Request.err('用户名重复,请重新注册'))
  }
  if (!req.body.img) {
   req.body.img = 'http://localhost:3000/public/img/1722762784928.png'
  }
  if (req.body.password) {
   req.body.password = bcrypt.hashSync(req.body.password, 10)
  }
  const model = await User.create(req.body)
  if (!model.id) {
   return res.send(Request.err())
  }
  res.send(Request.ok(model))

 })
 // 错误处理函数
 app.use(async (err, req, res, next) => {
  res.status(200).send({
   code: err.statusCode || 500,
   message: err.message,
  })
 })
}
